package com.ruoyi.server.util;

import com.ruoyi.framework.ws.WebSocketServer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class DataFormat {
    public WebSocketServer getWebSocketServer() {
        return webSocketServer;
    }

    public void setWebSocketServer(WebSocketServer webSocketServer) {
        this.webSocketServer = webSocketServer;
    }

    WebSocketServer webSocketServer;
    public DataFormat() {

    }

    public DataFormat(WebSocketServer webSocketServer) {
        this.webSocketServer = webSocketServer;
    }

    // 报头长度
    private static final int HEADER_SIZE = 16;
    // 数据长度字段长度
    private static final int LENGTH_SIZE = 2;
    // 数据块最大长度
    private static final int MAX_DATA_SIZE = 65535; // 2 bytes can hold max 65535
    // 检验和长度
    private static final int CHECKSUM_SIZE = 1;

    private static List<String> list = new ArrayList<>();
    private static List<String> liste000 = new ArrayList<>();
    private static List<String> liste001 = new ArrayList<>();
    private static List<String> liste002 = new ArrayList<>();
    private static List<String> liste003 = new ArrayList<>();
    private static List<String> liste000Hex = new ArrayList<>();
    private static List<String> liste001Hex = new ArrayList<>();
    private static List<String> liste002Hex = new ArrayList<>();
    private static List<String> liste003Hex = new ArrayList<>();

    // 解析方法
    public byte[][] parseData(byte[] data) {
        ByteBuf dataByteBuf = Unpooled.wrappedBuffer(data);
        if (data.length < HEADER_SIZE + LENGTH_SIZE) {
            throw new IllegalArgumentException("Insufficient data");
        }

        byte[] header = new byte[HEADER_SIZE];
        dataByteBuf.readBytes(header);

        byte baowentype = header[2];
        String type = ByteUtil.hexToStr(baowentype);
//        System.out.println(type);
        byte[] bodyLen = new byte[2];
        dataByteBuf.readBytes(bodyLen);

        ByteBuf bodyLenBuffer = Unpooled.wrappedBuffer(bodyLen);
        int len = bodyLenBuffer.readShortLE();
        byte[] dataBody = new byte[len];
        dataByteBuf.readBytes(dataBody);
        return new byte[][]{header, dataBody};
    }

    public void bodyParse(byte[][] data) {
        byte[] head = data[0];
        byte[] body = data[1];
        byte baowentype = head[2];
        String type = ByteUtil.hexToStr(baowentype);
        if (type.toUpperCase().equals("D1")) {
            ByteBuf bodyByteBuf = Unpooled.wrappedBuffer(body);
            while (bodyByteBuf.isReadable()) {
                deString(bodyByteBuf);
            }
        }
    }

    private void deString(ByteBuf bodyByteBuf) {
        byte[] dataTypeByte = new byte[2];
        bodyByteBuf.readBytes(dataTypeByte);
        String datatype = ByteUtil.hexToStr(dataTypeByte);
        byte[] lenByte = new byte[2];
        bodyByteBuf.readBytes(lenByte);
        int len = readShortLE(lenByte);
        byte[] cBody = new byte[len];
        bodyByteBuf.readBytes(cBody);
        String b = ByteUtil.hexToStr(cBody);
        System.out.println(datatype);
        try {

//        System.out.println(b);
            ByteBuf cBodyByteBuf = Unpooled.wrappedBuffer(cBody);
            //心率图
            if (datatype.equals("e001")) {

                System.out.println("质量:" + readShortLE(cBody[12]));
                System.out.println("心率值:" + readShortLE(cBody[14], cBody[15]));
                System.out.println("波形数据块个数:" + readShortLE(cBody[16], cBody[17]));
                byte[] body = new byte[23 - 3];
                cBodyByteBuf.readBytes(body);
                clear();
                while (cBodyByteBuf.isReadable()) {
                    byte[] d = new byte[1];
                    byte aab0 = cBodyByteBuf.readByte();
                    liste000Hex.add(ByteUtil.hexToStr(aab0));
                    String aa0 = readShortLE(aab0) + "";
                    liste000.add(aa0);

                    String aa02bin = Integer.toBinaryString(Integer.parseInt(aa0));
                    char b3 = '0';
                    char b2 = '0';
                    if (aa02bin.length() > 3) {
                        b3 = aa02bin.charAt(aa02bin.length() - 4);
                        b2 = aa02bin.charAt(aa02bin.length() - 3);
                    }else if(aa02bin.length()==3) {
                        b2 = aa02bin.charAt(aa02bin.length() - 3);

                    }
                    byte aab1 = cBodyByteBuf.readByte();
                    liste001Hex.add(ByteUtil.hexToStr(aab1));
                    String aa1 = Integer.parseInt(String.valueOf(b2) + ByteUtil.hexToStr(aab1), 16) + "";
                    if (b3 == '1') {
                        aa1 = (Integer.parseInt(ByteUtil.hexToStr(aab1),16) - 256) + "";
                    }
                    liste001.add(aa1);

                    byte aab2 = cBodyByteBuf.readByte();
                    liste002Hex.add(ByteUtil.hexToStr(aab2));
                    String aa2 = readShortLE(aab2) + "";
                    liste002.add(aa2);

                    byte aab3 = cBodyByteBuf.readByte();
                    liste003Hex.add(ByteUtil.hexToStr(aab3));
                    String aa3 = readShortLE(aab3) + "";
                    liste003.add(aa3);

                    System.out.print(ByteUtil.hexToStr(aab0) + ":");
                    System.out.print(ByteUtil.hexToStr(aab1) + ":");
                    System.out.print(ByteUtil.hexToStr(aab2) + ":");
                    System.out.println(ByteUtil.hexToStr(aab3) + "");

                }
//                System.out.println("liste001 size:" + liste001.size());
            } else if (datatype.equals("e304")) {

            } else if (datatype.equals("e503")) {
//                byte[] body = new byte[28 - 4];
//                cBodyByteBuf.readBytes(body);
//                System.out.print(readShortLE(body[10], body[11]) + "<<<");
//                System.out.print(readShortLE(body[12], body[13]) + "<<<");
//                System.out.print(readShortLE(body[14], body[15]) + "<<<");
//                System.out.print(readShortLE(body[16], body[17]) + "<<<");
//                while (cBodyByteBuf.isReadable()) {
//                    byte[] d = new byte[2];
//                    cBodyByteBuf.readBytes(d);
//                    System.out.print(readShortLE(d) + "->");
//                }
//                System.out.println();
            } else if (datatype.equals("e20b")) {
                System.out.print(readShortLE(cBody[0], cBody[1]) + "<<<");
                System.out.print(ByteUtil.hexToStr(cBody[2]));
                System.out.println();
            } else if (datatype.equals("e102")) {
                System.out.println("信号质量指数:" + readShortLE(cBody[4]));
                System.out.println("血氧值（%）:" + readShortLE(cBody[5]));
                System.out.println("灌注指数（%）:" + readShortLE(cBody[6], cBody[7]));
                System.out.println("脉率值(bpm):" + readShortLE(cBody[8], cBody[9]));
                System.out.println("呼吸率(rpm):" + readShortLE(cBody[10]));
                System.out.println("波形数据块个数:" + readShortLE(cBody[11], cBody[12]));
                byte[] body = new byte[16 - 3];
                cBodyByteBuf.readBytes(body);
                while (cBodyByteBuf.isReadable()) {
                    byte[] d = new byte[1];
//                cBodyByteBuf.readBytes(d);
                    ByteUtil.hexToStr(cBodyByteBuf.readByte());

                    // System.out.println(ByteUtil.hexToStr(cBodyByteBuf.readByte()));
                    if (cBodyByteBuf.isReadable()) {
                        byte[] a = new byte[1];
                        cBodyByteBuf.readBytes(a);
                        String aa = readShortLE(a[0]) + "";
//                        webSocketServer.onMessage(aa, null);
                        list.add(aa);
                    }
//                cBodyByteBuf.readBytes(d2);

//                System.out.println(ByteUtil.hexToStr(d2));

                }
            } else if (datatype.equals("e432")) {
                System.out.println("体温:" + readShortLE(cBody[5], cBody[6]) / 100);
            } else {
                System.out.println("unsupport:" + datatype);


            }
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (list.size() > 300) {
                webSocketServer.onMessage(String.join(",", list), null);
                list.clear();
            }
            if (liste001.size() > 300) {
                clear();
            }
        }
        System.out.println("size:" + list.size());
        System.out.println(String.join(",", list));

        if (datatype.equals("e001")) {
            System.out.println("liste000:" + liste000.size());
            System.out.println(String.join(",", liste000));
            System.out.println(String.join(",", liste000Hex));
            System.out.println("liste001:" + liste001.size());
//            webSocketServer.onMessage(String.join(",", liste001), null);
            System.out.println(String.join(",", liste001));
            System.out.println(String.join(",", liste001Hex));
            System.out.println("liste002:" + liste002.size());
            System.out.println(String.join(",", liste002));
            System.out.println(String.join(",", liste002Hex));
            System.out.println("liste003:" + liste003.size());
            System.out.println(String.join(",", liste003));
            System.out.println(String.join(",", liste003Hex));
        }

    }

    private static void clear() {
        liste000.clear();
        liste000Hex.clear();
        liste001.clear();
        liste001Hex.clear();
        liste002.clear();
        liste002Hex.clear();
        liste003.clear();
        liste003Hex.clear();
    }
    // 计算校验和的方法
    private static byte computeChecksum(byte[] header, byte[] payload) {
        int sum = 0;
        for (byte b : header) {
            sum += Byte.toUnsignedInt(b);
        }
        for (byte b : payload) {
            sum += Byte.toUnsignedInt(b);
        }
        return (byte) (sum & 0xFF); // 取最后8位
    }

    public static int readShortLE(byte[] b) {
        ByteBuf bodyLenBuffer = Unpooled.wrappedBuffer(b);
        int len = bodyLenBuffer.readUnsignedShortLE();
        return len;
    }

    public static int readShortLE(byte b1, byte b2) {
        byte[] b = new byte[2];
        b[0] = b1;
        b[1] = b2;
        ByteBuf bodyLenBuffer = Unpooled.wrappedBuffer(b);
        int len = bodyLenBuffer.readUnsignedShortLE();
        return len;
    }

    public static int readShortLE(String hex) {
        return readShortLE(ByteUtil.hexStr2Byte(hex));
    }

    public static int readShortLE(byte b1) {
        byte[] b = new byte[2];
        b[0] = b1;
        b[1] = (byte) 0;
        return readShortLE(b);
    }

//    public static void main(String[] args) {
//        String s = "aaabd1000100f11000010000000000002904e0016c020000050000400001000000000000ffff96000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000e102d50000000000636217044900006400004800460045004500430043004200420042004600490052015802580366036e047f058606860694079a07a408a708a709ad09af09b109b109b109b109b109af09ad08ad08aa08a708a308a007a0079b07990795069306930690068f068c068b068b06890588058605860586058405820580047f047f047c047b04770476037603720371036e036c026c0269026802650264026402620261015e015d015d015b015a0158015701570155015400530052005200530155015b01600160026b02710380038705870595e20b0300490001e304d50000000100ff03000000000064000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000dd";
//        byte[][] sa = parseData(ByteUtil.hexStr2Byte(s));
//        bodyParse(sa);
//    }
}